package LeetCode.algorithms.addTwoNumbers;

public class Solution {
	public static void main(String[] args) {
		ListNode l1 = new ListNode(2);
		ListNode l11 = new ListNode(4);
		ListNode l111 = new ListNode(3);
		l1.next = l11;
		l11.next = l111;
		ListNode l2 = new ListNode(5);
		ListNode l22 = new ListNode(6);
		// ListNode l222 = new ListNode(6);
		l2.next = l22;
		// l22.next = l222;

		/*
		 * while (l1 != null) { System.out.println(l1.val); l1 = l1.next; }
		 */
		ListNode l = addTwoNumbers2(l1, l2);
		while (l != null) {
			System.out.print(l.val + " ");
			l = l.next;
		}
	}

	public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
		ListNode listNode = new ListNode(0);
		int sum = 0, val = 0;
		if (l1 == null || l2 == null) {
			listNode.val = l1 != null ? l1.val : 0;
			listNode.val = l2 != null ? l2.val : 0;
			if (listNode.val % 10 != 0) {
				val = listNode.val / 10;
				ListNode nListNode = new ListNode(val);
				listNode.next = nListNode;
			}
			return listNode;
		}

		sum = l1.val + l2.val;
		val = sum / 10;
		listNode.val = val == 0 ? sum : sum % 10;

		ListNode item1 = l1.next;
		ListNode item2 = l2.next;
		ListNode itemNode = listNode;
		while (item1 != null || item2 != null) {
			if (item1 == null) {
				sum = item2.val + val;
			}
			if (item2 == null) {
				sum = item1.val + val;
			}
			if (item1 != null && item2 != null) {
				sum = item1.val + item2.val + val;
			}

			val = sum / 10;
			ListNode newNode = new ListNode(0);
			if (val == 0) {
				newNode.val += sum;
			} else {
				newNode.val += sum % 10;
			}
			itemNode.next = newNode;
			itemNode = itemNode.next;
			item1 = item1 != null ? item1.next : null;
			item2 = item2 != null ? item2.next : null;
		}
		if (val != 0) {
			ListNode nListNode = new ListNode(val);
			itemNode.next = nListNode;
		}
		return listNode;
	}

	private static ListNode addTwoNumbers2(ListNode l1, ListNode l2) {
		ListNode prev = new ListNode(0);
		ListNode head = prev;
		int carry = 0;
		while (l1 != null || l2 != null || carry != 0) {
			ListNode cur = new ListNode(0);
			int sum = ((l2 == null) ? 0 : l2.val) + ((l1 == null) ? 0 : l1.val) + carry;
			cur.val = sum % 10;
			carry = sum / 10;
			prev.next = cur;
			prev = cur;

			l1 = (l1 == null) ? l1 : l1.next;
			l2 = (l2 == null) ? l2 : l2.next;
		}
		return head.next;
	}

	private static class ListNode {
		int val;
		ListNode next;

		ListNode(int x) {
			val = x;
		};
	}
}
